#!/usr/bin/python
# -*- coding: utf-8 -*-
# @version        : 1.0
# @Creaet Time    : 2022/3/21 11:03 
# @File           : event.py
# @IDE            : PyCharm
# @desc           : 全局事件

from fastapi import FastAPI
from aioredis import from_url  # pip install aioredis
from application.settings import REDIS_DB_CONFIG  # 项目配置文件添加 redis 配置


def register_redis(app: FastAPI) -> None:
    """
    把redis挂载到app对象上面

    博客：https://blog.csdn.net/wgPython/article/details/107668521
    博客：https://www.cnblogs.com/emunshe/p/15761597.html
    官网：https://aioredis.readthedocs.io/en/latest/getting-started/
    :param app:
    :return:
    """

    @app.on_event('startup')
    async def startup_event():
        """
        获取链接
        :return:
        """
        print("获取redis链接")
        app.state.redis = from_url(REDIS_DB_CONFIG.get("db_url"), port=REDIS_DB_CONFIG.get("db_port")
                                   , password=REDIS_DB_CONFIG.get("db_password"), db=REDIS_DB_CONFIG.get("db")
                                   , encoding=REDIS_DB_CONFIG.get("db_encoding"), decode_responses=True)

    @app.on_event('shutdown')
    async def shutdown_event():
        """
        关闭
        :return:
        """
        print("关闭redis链接")
        app.state.redis.close()
        await app.state.redis.wait_closed()
